import Http from './request'
import store from '../../store';
import { BASE_URL } from '../api/auth.js'

let http = new Http({
	header: {
		'content-type': 'application/x-www-form-urlencoded'
	}
})

let clock
let reqCount = 0
const DELAY_TIME = 500

http.interceptors.request.use((config) => {
	// 正向代理请求
	config.url = BASE_URL + config.url;
	config.header['Accept-Language'] = 'zh-CN,zh;q=0.9';
	// 缓存中没有设置token，获取缓存中的游客token
	config.header.token = uni.getStorageSync('token');
	return config
}, (err) => {
	uni.showToast({
		icon: 'none',
		title: '网络错误',
		duration: 2000
	});
})

http.interceptors.response.use((res) => {
	if (!res || (res.statusCode !== 200 && res.statusCode !== 401)) {
		uni.showToast({
			icon: 'none',
			title: '网络错误',
			duration: 2000
		});
		return false;
	}
	// token过期
	if (res.statusCode == 401) {
		uni.showToast({
			icon: 'none',
			title: res.data.msg,
			duration: 2000
		});
		store.dispatch('user/logout');
		store.dispatch('user/setLogin', true);
		return false;
	}
	if (res.data.code !== 1) {
		uni.showToast({
			icon: 'none',
			title: res.data.msg,
			duration: 2000
		});
		return false;
	}
	return res.data;
}, (err) => {
	uni.hideLoading();
})

export default http
